package org.groupg.demo.sshd;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.scp.client.ScpClient;
import org.apache.sshd.scp.client.ScpClientCreator;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

public class ScpClientExample {
    public static void main(String[] args) throws Exception {
        SshClient client = SshClient.setUpDefaultClient();
        client.start();

        try (ClientSession session = client.connect("username", "hostname", 22)
                .verify(5000, TimeUnit.MILLISECONDS)
                .getSession()) {

            session.addPasswordIdentity("password");
            session.auth().verify(5000, TimeUnit.MILLISECONDS);

            ScpClientCreator creator = ScpClientCreator.instance();
            ScpClient scp = creator.createScpClient(session);

            // 下载文件
            Path localPath = Paths.get("/local/path");
            scp.download("/remote/file.txt", localPath);

            // 上传文件
            Path localFile = Paths.get("/local/file.txt");
            scp.upload(localFile, "/remote/path/");
        } finally {
            client.stop();
        }
    }
}
